
package br.com.aeternu.controleatendimento.excel.agenda;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import br.com.aeternu.controleatendimento.common.bean.CommonBean;
import br.com.aeternu.controleatendimento.common.ifc.IfcMensagemUsuario;
import br.com.aeternu.controleatendimento.excel.Excel;
import br.com.aeternu.controleatendimento.exception.ControleAtendimentoException;
import br.com.aeternu.controleatendimento.util.DateUtil;

public class ExcelAgenda extends Excel
{

   private static Logger logger = Logger.getLogger(ExcelAgenda.class);
   private static final String SHEET = SHEET_AGENDAS;

   public ExcelAgenda() throws ControleAtendimentoException
   {
      super();

      if (!temAgenda())
      {
         novaAgenda();
      }
   }

   @Override
   public void atualiza(CommonBean bean)
   {
      AgendaBean agendaBean = (AgendaBean) bean;

      try
      {
         HSSFWorkbook workbook = obterPastaDeTrabalho();

         HSSFSheet sheet = getSheet(workbook);

         HSSFCellStyle cellStyle = getCellStyleGeral(workbook);
         HSSFRow row;
         HSSFCell cell;

         if (agendaBean.getLinha() > 0)
         {
            row = sheet.getRow(agendaBean.getLinha());
            // Data
            cell = row.getCell(0);
            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
            cell.setCellStyle(cellStyle);
            cell.setCellValue(dateFormat.format(agendaBean.getData()));
            // Agendas Matutino
            cell = row.getCell(1);
            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("General"));
            cell.setCellStyle(cellStyle);
            cell.setCellValue(agendaBean.getQtdeMatutino());
            // Agendas Vespertino
            cell = row.getCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(agendaBean.getQtdeVespertino());
         }
         else
         {
            row = sheet.createRow(sheet.getLastRowNum() + 1);
            agendaBean.setLinha(sheet.getLastRowNum());
            // Data
            cell = row.createCell(0);
            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
            cell.setCellStyle(cellStyle);
            cell.setCellValue(agendaBean.getData());
            // Agendas Matutino
            cell = row.createCell(1);
            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("General"));
            cell.setCellStyle(cellStyle);
            cell.setCellValue(agendaBean.getQtdeMatutino());
            // Agendas Vespertino
            cell = row.createCell(2);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(agendaBean.getQtdeVespertino());
         }

         gravar(workbook);

         logger.info(SHEET + ": Linha " + agendaBean.getLinha() + " atualizada com sucesso!");
      }
      catch (ControleAtendimentoException e)
      {
         logger.error(e.getMessage(), e);
      }
      catch (FileNotFoundException e)
      {
         logger.error(e.getMessage(), e);
      }
      catch (IOException e)
      {
         logger.error(e.getMessage(), e);
      }
   }

   @Override
   public void atualiza(List<? extends CommonBean> beanList)
   {
      @SuppressWarnings("unchecked")
      List<AgendaBean> agendaBeanList = (List<AgendaBean>) beanList;

      for (AgendaBean bean : agendaBeanList)
      {
         atualiza(bean);
      }
   }

   public void novaAgenda() throws ControleAtendimentoException
   {
      Calendar calendar = Calendar.getInstance();
      HSSFWorkbook workbook = obterPastaDeTrabalho();
      HSSFSheet sheet = getSheet(workbook);
      int lastRowNum = sheet.getLastRowNum();
      HSSFRow row = sheet.getRow(lastRowNum);
      HSSFCellStyle cellStyle = getCellStyleGeral(workbook);
      Date maiorData = null;

      if (row != null && row.getCell(0) != null)
         maiorData = getDate(row.getCell(0));

      if (maiorData == null)
      {
         calendar.set(calendar.get(Calendar.YEAR), Calendar.JANUARY, calendar.getMinimum(Calendar.DAY_OF_YEAR));
      }
      else
      {
         calendar.setTime(maiorData);
         calendar.add(Calendar.DAY_OF_YEAR, 1);
      }

      for (int i = 1; i < calendar.getMaximum(Calendar.DAY_OF_YEAR); i++)
      {
         row = sheet.createRow(lastRowNum + 1);

         HSSFCell cell = row.createCell(0);
         cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
         cell.setCellStyle(cellStyle);
         cell.setCellValue(dateFormat.format(calendar.getTime()));

         cell = row.createCell(1);
         cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("General"));
         cell.setCellStyle(cellStyle);
         cell.setCellValue((DateUtil.isUtil(calendar) ? 1 : 0));

         cell = row.createCell(2);
         cell.setCellStyle(cellStyle);
         cell.setCellValue((DateUtil.isUtil(calendar) ? 1 : 0));

         calendar.add(Calendar.DAY_OF_YEAR, 1);
         lastRowNum++;

         logger.info(SHEET + ": Linha " + sheet.getLastRowNum() + " atualizada com sucesso!");
      }

      try
      {
         gravar(workbook);
      }
      catch (IOException e)
      {
         logger.error(e.getMessage(), e);
      }
   }

   public List<AgendaBean> obterRegistros() throws ControleAtendimentoException
   {
      List<AgendaBean> agendaBeanList = new ArrayList<AgendaBean>();

      HSSFSheet sheet = getSheet();

      for (Iterator<Row> rit = (Iterator<Row>) sheet.rowIterator(); rit.hasNext();)
      {
         HSSFRow row = (HSSFRow) rit.next();
         AgendaBean bean = new AgendaBean();

         // pulando o cabeçalho
         if (row.getRowNum() > 0 && row.getCell(0) != null)
         {
            if (row.getRowNum() == 1 && getDate(row.getCell(0)) == null)
            {
               // Primeira linha não possui dado válido
               throw new ControleAtendimentoException(IfcMensagemUsuario.ERRO_AGENDA_NAO_ENCONTRADA);
            }

            bean.setLinha(row.getRowNum());
            bean.setData(getDate(row.getCell(0)));
            bean.setQtdeMatutino(getInteger(row.getCell(1)));
            bean.setQtdeVespertino(getInteger(row.getCell(2)));

            agendaBeanList.add(bean);
         }
      }

      return agendaBeanList;
   }

   @Override
   protected HSSFSheet getSheet() throws ControleAtendimentoException
   {
      HSSFWorkbook workbook = obterPastaDeTrabalho();

      return getSheet(workbook);
   }

   protected HSSFSheet getSheet(HSSFWorkbook workbook) throws ControleAtendimentoException
   {
      HSSFSheet sheet = workbook.getSheet(SHEET);

      if (sheet == null)
      {
         criarNovaPlanilhaAgendas(workbook, getCellStyleCabecalho(workbook), getCellStyleGeral(workbook));
         workbook = obterPastaDeTrabalho();
         sheet = workbook.getSheet(SHEET);
      }

      return sheet;
   }

   private boolean temAgenda() throws ControleAtendimentoException
   {
      HSSFSheet sheet = getSheet();
      HSSFRow row = sheet.getRow(sheet.getLastRowNum());

      if (row != null)
      {
         Date maiorData = getDate(row.getCell(0));

         if (maiorData == null)
            return false;

         return true;
      }
      else
      {
         return false;
      }
   }
}
